package com.company.genealogy.web.service.impl;

import com.company.genealogy.web.service.HomeService;
import com.company.genealogy.web.mapper.MemberMapper;
import com.company.genealogy.web.mapper.BranchMapper;
import com.company.genealogy.web.mapper.FamilyNewsMapper;
import com.company.genealogy.web.mapper.ReminderMapper;
import com.company.genealogy.web.mapper.FamilyEventMapper;
import com.company.genealogy.web.mapper.UserContributionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 首页服务实现类
 */
@Service
public class HomeServiceImpl implements HomeService {

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private BranchMapper branchMapper;

    @Autowired
    private FamilyNewsMapper familyNewsMapper;

    @Autowired
    private ReminderMapper reminderMapper;

    @Autowired
    private FamilyEventMapper familyEventMapper;

    @Autowired
    private UserContributionMapper userContributionMapper;

    @Override
    public List<Map<String, Object>> getTodayReminders() {
        List<Map<String, Object>> reminders = new ArrayList<>();
        
        // 获取今日生日提醒
//        List<Map<String, Object>> birthdays = memberMapper.getTodayBirthdays();
//        for (Map<String, Object> birthday : birthdays) {
//            Map<String, Object> reminder = new HashMap<>();
//            reminder.put("id", "birthday_" + birthday.get("id"));
//            reminder.put("icon", "🎂");
//            reminder.put("text", birthday.get("name") + " 今天生日");
//            reminder.put("type", "birthday");
//            reminders.add(reminder);
//        }

        // 获取今日重要事件
        List<Map<String, Object>> events = reminderMapper.getTodayReminders();
        for (Map<String, Object> event : events) {
            Map<String, Object> reminder = new HashMap<>();
            reminder.put("id", "event_" + event.get("id"));
            reminder.put("icon", event.get("icon") != null ? event.get("icon") : "📅");
            reminder.put("text", event.get("title"));
            reminder.put("type", "event");
            reminders.add(reminder);
        }

        return reminders;
    }

    @Override
    public Map<String, Object> getFamilyStats(Long clanId) {
        Map<String, Object> stats = new HashMap<>();
        // 总人数
        Integer totalMembers = memberMapper.countTotalMembersByClanId(clanId);
        stats.put("totalMembers", totalMembers != null ? totalMembers : 0);
        // 世代数
        Integer maxGeneration = memberMapper.getMaxGenerationByClanId(clanId);
        stats.put("generations", maxGeneration != null ? maxGeneration : 0);
        // 分支数
        Long totalBranches = branchMapper.countTotalBranchesByClanId(clanId);
        stats.put("branches", totalBranches != null ? totalBranches : 0);
        // 活跃成员（最近30天有更新的）
        Integer activeMembers = memberMapper.countActiveMembersByLogin(clanId);
        stats.put("activeMembers", activeMembers != null ? activeMembers : 0);
        return stats;
    }

    @Override
    public Map<String, Object> getFamilyNews(int page, int size, Long clanId) {
        Map<String, Object> result = new HashMap<>();
        int offset = (page - 1) * size;
        List<Map<String, Object>> newsList = familyNewsMapper.getNewsListByClanId(offset, size, clanId);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        for (Map<String, Object> news : newsList) {
            if (news.get("created_at") != null) {
                news.put("createTime", news.get("created_at").toString());
            }
            // 确保view_count字段存在，如果为null则设为0
            if (news.get("view_count") == null) {
                news.put("view_count", 0);
            }
            // 确保like_count字段存在，如果为null则设为0
            if (news.get("like_count") == null) {
                news.put("like_count", 0);
            }
        }
        result.put("list", newsList);
        result.put("total", familyNewsMapper.countTotalNewsByClanId(clanId));
        result.put("page", page);
        result.put("size", size);
        return result;
    }
    
    @Override
    public List<Map<String, Object>> getNewsLikes(List<Long> newsIds) {
        return familyNewsMapper.getNewsLikes(newsIds);
    }

    @Override
    public List<Map<String, Object>> getHotBranches(int limit, Long clanId) {
        return branchMapper.getHotBranches(limit, clanId);
    }

    @Override
    public Map<String, Object> getUserContributions() {
        Map<String, Object> result = new HashMap<>();
        
        // 获取贡献排行榜
        List<Map<String, Object>> topContributors = userContributionMapper.getTopContributors(10L, 1);
        result.put("topContributors", topContributors);
        
        // 获取当前用户贡献
        Long currentUserContributions = 0L;
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication != null && authentication.isAuthenticated()) {
                String userIdStr = authentication.getName();
                Long userId = Long.parseLong(userIdStr);
                currentUserContributions = userContributionMapper.getCurrentUserContributions(userId);
            }
        } catch (Exception e) {
            // 如果获取当前用户失败，设置为0
            currentUserContributions = 0L;
        }
        result.put("currentUserContributions", currentUserContributions != null ? currentUserContributions : 0);
        
        return result;
    }

    @Override
    public List<Map<String, Object>> getUpcomingEvents(int limit) {
        return familyEventMapper.getUpcomingEvents(limit);
    }

    @Override
    public Map<String, Object> getPopulationDistribution() {
        Map<String, Object> result = new HashMap<>();
        
        // 按分支统计人口分布
        List<Map<String, Object>> branchDistribution = memberMapper.getPopulationByBranch();
        result.put("branchDistribution", branchDistribution);
        
        // 按地区统计人口分布
        List<Map<String, Object>> regionDistribution = memberMapper.getPopulationByRegion();
        result.put("regionDistribution", regionDistribution);
        
        return result;
    }

    @Override
    public Map<String, Object> getGenerationStats() {
        Map<String, Object> result = new HashMap<>();
        
        // 各世代人数统计
        List<Map<String, Object>> generationStats = memberMapper.getGenerationStats();
        result.put("generationStats", generationStats);
        
        // 世代人数趋势
        List<Map<String, Object>> generationTrend = memberMapper.getGenerationTrend();
        result.put("generationTrend", generationTrend);
        
        return result;
    }

    @Override
    public Map<String, Object> getAgeStructure() {
        Map<String, Object> result = new HashMap<>();
        
        // 年龄结构分析
//        List<Map<String, Object>> ageGroups = memberMapper.getAgeStructure();
//        result.put("ageGroups", ageGroups);

        // 性别比例
//        List<Map<String, Object>> genderRatio = memberMapper.getGenderRatio();
//        result.put("genderRatio", genderRatio);
        
        return result;
    }

    @Override
    public Map<String, Object> getDashboard() {
        Map<String, Object> dashboard = new HashMap<>();
        // 基础统计（兼容老用法，默认查全部）
        dashboard.put("stats", getFamilyStats(null));
        // 今日提醒
        dashboard.put("reminders", getTodayReminders());
        // 最新动态
        dashboard.put("news", getFamilyNews(1, 3, null)); // Assuming clanId is not needed for this call
        // 热门分支
        dashboard.put("hotBranches", getHotBranches(3, null)); // Assuming clanId is not needed for this call
        // 即将到来的活动
        dashboard.put("upcomingEvents", getUpcomingEvents(3));
        // 人口分布
        dashboard.put("populationDistribution", getPopulationDistribution());
        return dashboard;
    }
} 